﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace AssemblyViewer.Common
{
    class AssemblyHelper
    {
        private static readonly IList<string> IgnoreAssemblies = new List<string>() { "mscorlib" };

        /// <summary>
        /// 加载程序集
        /// </summary>
        /// <param name="assemblyString">程序集的FullName</param>
        /// <param name="assemblyFile">程序集文件路径</param>
        /// <returns></returns>
        public static Assembly Load(string assemblyString, string assemblyFile)
        {
            Assembly loadedAssembly;
            try
            {
                loadedAssembly = Assembly.Load(assemblyString);
            }
            catch (FileNotFoundException)
            {
                try
                {
                    loadedAssembly = Assembly.LoadFrom(assemblyFile);
                }
                catch (FileNotFoundException)
                {
                    return null;
                }
            }

            return loadedAssembly;
        }

        /// <summary>
        /// 检查程序集
        /// </summary>
        /// <param name="assemblyString">程序集的FullName</param>
        /// <param name="assemblyFile">程序集文件路径</param>
        /// <returns></returns>
        public static string ValidateAssembly(string assemblyString, string assemblyFile)
        {
            if (IgnoreAssemblies.Any<string>((ignoreAssembly) => { return assemblyString.IndexOf(ignoreAssembly) != -1; }))
            {
                return string.Empty;
            }

            string remark = string.Empty;
            try
            {
                Assembly loadedAssembly;
                try
                {
                    loadedAssembly = Assembly.ReflectionOnlyLoad(assemblyString);
                }
                catch (FileNotFoundException)
                {
                    loadedAssembly = Assembly.ReflectionOnlyLoadFrom(assemblyFile);
                }

                if (string.Compare(assemblyString, loadedAssembly.FullName) != 0)
                {
                    remark = string.Format("与该程序集版本[{0}]不一致", loadedAssembly.FullName);
                }
            }
            catch (FileNotFoundException)
            {
                remark = "该程序集未找到";
            }
            catch (BadImageFormatException)
            {
                remark = "该程序集和当前程序的目标平台不一致";
            }
            catch (Exception ex)
            {
                remark = ex.Message;
            }

            return remark;
        }
    }
}
